import request from '@/utils/request'

// 客户分页
export function getCustomerPage(params) {
  return request({ url: '/api/sales/customer/page', method: 'get', params })
}

// 客户CRUD
export function createCustomer(data) {
  return request({ url: '/api/sales/customer', method: 'post', data })
}

export function updateCustomer(id, data) {
  return request({ url: `/api/sales/customer/${id}`, method: 'put', data })
}

export function deleteCustomer(id) {
  return request({ url: `/api/sales/customer/${id}`, method: 'delete' })
}

// 批量删除
export function deleteCustomerBatch(ids) {
  // 使用 DELETE 并按 ids 多值传参：/customer/batch?ids=1&ids=2
  const params = new URLSearchParams()
  ;(Array.isArray(ids) ? ids : [ids]).forEach(id => params.append('ids', id))
  return request({ url: `/api/sales/customer/batch?${params.toString()}` , method: 'delete' })
}

// ---------- 订单 ----------
// 创建完整订单（包含明细）
export function createFullOrder(data) {
  return request({ url: '/api/sales/order/full', method: 'post', data })
}

// 更新完整订单（包含明细）
export function updateFullOrder(id, data) {
  return request({ url: `/api/sales/order/full/${id}`, method: 'put', data })
}

// 基础订单操作
export function createOrder(data) {
  return request({ url: '/api/sales/order', method: 'post', data })
}

export function getOrderPage(params) {
  return request({ url: '/api/sales/order/page', method: 'get', params })
}

// 高级查询订单
export function getOrderPageAdvanced(data) {
  return request({ url: '/api/sales/order/page/advanced', method: 'post', data })
}

export function updateOrder(id, data) {
  return request({ url: `/api/sales/order/${id}`, method: 'put', data })
}

export function deleteOrderBatch(ids) {
  const p = new URLSearchParams(); (Array.isArray(ids)?ids:[ids]).forEach(id=>p.append('ids',id))
  return request({ url: `/api/sales/order/batch?${p.toString()}`, method: 'delete' })
}

export function getOrderDetail(id) {
  return request({ url: `/api/sales/order/${id}`, method: 'get' })
}

// 获取完整订单详情（包含明细和客户信息）
export function getFullOrderDetail(id) {
  return request({ url: `/api/sales/order/${id}/full`, method: 'get' })
}

export function getOrderPrintData(id) {
  return request({ 
    url: `/api/sales/order/${id}/print`, 
    method: 'get',
    responseType: 'blob'
  })
}

// 批量打印订单
export function printOrdersBatch(ids) {
  const params = new URLSearchParams()
  ;(Array.isArray(ids) ? ids : [ids]).forEach(id => params.append('ids', id))
  return request({ 
    url: `/api/sales/order/print/batch?${params.toString()}`, 
    method: 'post',
    responseType: 'blob'
  })
}

// 订单状态管理
export function submitOrder(id) {
  return request({ url: `/api/sales/order/${id}/submit`, method: 'post' })
}

export function approveOrder(id, approvalRemark) {
  return request({ 
    url: `/api/sales/order/${id}/approve`, 
    method: 'post',
    params: { approvalRemark }
  })
}

export function rejectOrder(id, rejectReason) {
  return request({ 
    url: `/api/sales/order/${id}/reject`, 
    method: 'post',
    params: { rejectReason }
  })
}

export function closeOrder(id, closeReason) {
  return request({ 
    url: `/api/sales/order/${id}/close`, 
    method: 'post',
    params: { closeReason }
  })
}

// 根据客户ID查询订单
export function getOrdersByCustomerId(customerId) {
  return request({ url: `/api/sales/order/customer/${customerId}`, method: 'get' })
}

// 获取订单统计信息
export function getOrderStats() {
  return request({ url: '/api/sales/order/stats', method: 'get' })
}

// ---------- 退货订单 ----------
export function createReturnOrder(data) {
  return request({ url: '/api/sales/return-order', method: 'post', data })
}

export function updateReturnOrder(id, data) {
  return request({ url: `/api/sales/return-order/${id}`, method: 'put', data })
}

export function getReturnOrderDetail(id) {
  return request({ url: `/api/sales/return-order/${id}`, method: 'get' })
}

export function getReturnOrderPage(params) {
  return request({ url: '/api/sales/return-order/page', method: 'get', params })
}

export function approveReturnOrder(id) {
  return request({ url: `/api/sales/return-order/${id}/approve`, method: 'post' })
}

export function rejectReturnOrder(id, rejectReason) {
  return request({ 
    url: `/api/sales/return-order/${id}/reject`, 
    method: 'post',
    params: { rejectReason }
  })
}

export function processReturnOrder(id) {
  return request({ url: `/api/sales/return-order/${id}/process`, method: 'post' })
}

export function getReturnOrdersBySalesOrder(salesOrderId) {
  return request({ url: `/api/sales/return-order/sales-order/${salesOrderId}`, method: 'get' })
}

export function deleteReturnOrder(id) {
  return request({ url: `/api/sales/return-order/${id}`, method: 'delete' })
}

export function getReturnOrderStats() {
  return request({ url: '/api/sales/return-order/stats', method: 'get' })
}

// ---------- 产品相关 ----------
export function getProductOptions(params) {
  // 商品服务 ProductController：/api/product/page，参数 productName/pageNo/pageSize
  const query = { productName: params?.keyword || params?.productName || '', pageNo: params?.pageNo || 1, pageSize: params?.pageSize || 50 }
  return request({ url: '/api/product/page', method: 'get', params: query })
}

export function getProductDetail(id) {
  return request({ url: `/api/product/${id}`, method: 'get' })
}

// SKU 分页（按 productId 过滤）
export function getSkuPage(params) {
  return request({ url: '/api/sku/page', method: 'get', params })
}

export function getCustomerDetail(id) {
  return request({ url: `/api/sales/customer/${id}`, method: 'get' })
}

// 导出
export function exportCustomers(params) {
  return request({
    url: '/api/sales/customer/export',
    method: 'get',
    params,
    responseType: 'blob'
  })
}

// 导入
export function importCustomers(file) {
  const form = new FormData()
  form.append('file', file)
  return request({
    url: '/api/sales/customer/import',
    method: 'post',
    data: form,
    headers: { 'Content-Type': 'multipart/form-data' }
  })
}

// 员工下拉
export function getEmployeeOptions(params) {
  return request({ url: '/api/sales/employee/options', method: 'get', params })
}

// 附件管理相关接口
export const attachmentApi = {
  // 分页查询附件
  pageAttachments(params) {
    return request({
      url: '/api/sales/attachment/page',
      method: 'get',
      params
    })
  },

  // 根据订单ID查询附件列表
  getAttachmentsBySoId(soId) {
    return request({
      url: `/api/sales/attachment/order/${soId}`,
      method: 'get'
    })
  },

  // 根据订单ID查询有效附件列表
  getValidAttachmentsBySoId(soId) {
    return request({
      url: `/api/sales/attachment/order/${soId}/valid`,
      method: 'get'
    })
  },

  // 根据附件类型查询附件列表
  getAttachmentsByType(attachmentType) {
    return request({
      url: `/api/sales/attachment/type/${attachmentType}`,
      method: 'get'
    })
  },

  // 根据上传人查询附件列表
  getAttachmentsByUploader(uploader) {
    return request({
      url: `/api/sales/attachment/uploader/${uploader}`,
      method: 'get'
    })
  },

  // 统计订单附件数量
  countAttachmentsBySoId(soId) {
    return request({
      url: `/api/sales/attachment/count/${soId}`,
      method: 'get'
    })
  },

  // 统计订单有效附件数量
  countValidAttachmentsBySoId(soId) {
    return request({
      url: `/api/sales/attachment/count/${soId}/valid`,
      method: 'get'
    })
  },

  // 获取附件信息
  getAttachmentInfo(attachmentId) {
    return request({
      url: `/api/sales/attachment/info/${attachmentId}`,
      method: 'get'
    })
  },

  // 检查附件是否存在
  checkAttachmentExists(attachmentId) {
    return request({
      url: `/api/sales/attachment/exists/${attachmentId}`,
      method: 'get'
    })
  },

  // 更新附件描述
  updateAttachmentDescription(attachmentId, description) {
    return request({
      url: `/api/sales/attachment/${attachmentId}/description`,
      method: 'put',
      params: { description }
    })
  },

  // 获取允许的文件类型列表
  getAllowedFileTypes() {
    return request({
      url: '/api/sales/attachment/allowed-types',
      method: 'get'
    })
  },

  // 获取最大文件大小
  getMaxFileSize() {
    return request({
      url: '/api/sales/attachment/max-size',
      method: 'get'
    })
  },

  // 获取附件类型配置列表
  getAttachmentTypeConfigs() {
    return request({
      url: '/api/sales/attachment/type-configs',
      method: 'get'
    })
  },

  // 根据类型编码获取附件类型配置
  getAttachmentTypeConfigByCode(typeCode) {
    return request({
      url: `/api/sales/attachment/type-config/${typeCode}`,
      method: 'get'
    })
  }
}

// 附件类型配置管理接口
export const attachmentTypeApi = {
  // 分页查询附件类型配置
  pageAttachmentTypeConfigs(params) {
    return request({
      url: '/api/sales/attachment-type/page',
      method: 'get',
      params
    })
  },

  // 查询所有附件类型配置
  getAllAttachmentTypeConfigs() {
    return request({
      url: '/api/sales/attachment-type/list',
      method: 'get'
    })
  },

  // 根据状态查询附件类型配置
  getAttachmentTypeConfigsByStatus(status) {
    return request({
      url: `/api/sales/attachment-type/status/${status}`,
      method: 'get'
    })
  },

  // 根据类型编码查询附件类型配置
  getAttachmentTypeConfigByCode(typeCode) {
    return request({
      url: `/api/sales/attachment-type/code/${typeCode}`,
      method: 'get'
    })
  },

  // 查询所有启用的附件类型配置
  getEnabledAttachmentTypeConfigs() {
    return request({
      url: '/api/sales/attachment-type/enabled',
      method: 'get'
    })
  },

  // 创建附件类型配置
  createAttachmentTypeConfig(data) {
    return request({
      url: '/api/sales/attachment-type',
      method: 'post',
      data
    })
  },

  // 更新附件类型配置
  updateAttachmentTypeConfig(id, data) {
    return request({
      url: `/api/sales/attachment-type/${id}`,
      method: 'put',
      data
    })
  },

  // 删除附件类型配置
  deleteAttachmentTypeConfig(id) {
    return request({
      url: `/api/sales/attachment-type/${id}`,
      method: 'delete'
    })
  },

  // 批量删除附件类型配置
  deleteAttachmentTypeConfigs(ids) {
    return request({
      url: '/api/sales/attachment-type/batch',
      method: 'delete',
      data: ids
    })
  },

  // 启用附件类型配置
  enableAttachmentTypeConfig(id) {
    return request({
      url: `/api/sales/attachment-type/${id}/enable`,
      method: 'put'
    })
  },

  // 停用附件类型配置
  disableAttachmentTypeConfig(id) {
    return request({
      url: `/api/sales/attachment-type/${id}/disable`,
      method: 'put'
    })
  },

  // 检查文件类型是否允许
  checkFileTypeAllowed(fileName, typeCode) {
    return request({
      url: '/api/sales/attachment-type/check-file-type',
      method: 'get',
      params: { fileName, typeCode }
    })
  },

  // 获取文件大小限制
  getMaxFileSize(typeCode) {
    return request({
      url: `/api/sales/attachment-type/max-file-size/${typeCode}`,
      method: 'get'
    })
  },

  // 获取允许的文件扩展名列表
  getAllowedExtensions(typeCode) {
    return request({
      url: `/api/sales/attachment-type/allowed-extensions/${typeCode}`,
      method: 'get'
    })
  }
}

// 文件上传下载接口（使用axios处理文件，确保携带认证信息）
export const fileApi = {
  // 上传单个附件
  async uploadAttachment(soId, file, description, uploader) {
    const formData = new FormData()
    formData.append('soId', soId)
    formData.append('file', file)
    if (description) formData.append('description', description)
    if (uploader) formData.append('uploader', uploader)

    try {
      const response = await fetch('/api/sales/attachment/upload', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: formData
      })
      return response.json()
    } catch (error) {
      console.error('上传失败:', error)
      return { success: false, message: '上传失败' }
    }
  },

  // 批量上传附件
  async uploadAttachments(soId, files, description, uploader) {
    const formData = new FormData()
    formData.append('soId', soId)
    
    // 修复：使用正确的FormData构建方式
    // 对于多个文件，Spring Boot期望每个文件都有唯一的key
    files.forEach((file, index) => {
      console.log(`sales.js: 添加文件到FormData ${index + 1}:`, file)
      // 使用 'files[]' 或者直接使用 'files' 但确保Spring Boot能正确解析
      formData.append('files', file)
    })
    
    if (description) formData.append('description', description)
    if (uploader) formData.append('uploader', uploader)

    // 打印FormData内容用于调试
    console.log('FormData内容:')
    for (let [key, value] of formData.entries()) {
      if (value instanceof File) {
        console.log(`${key}:`, value.name, value.size, value.type)
      } else {
        console.log(`${key}:`, value)
      }
    }

    // 添加重试机制和更好的错误处理
    const maxRetries = 3
    let lastError = null
    
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        console.log(`尝试上传 (第${attempt}次):`, {
          url: '/api/sales/attachment/upload/batch',
          method: 'POST',
          filesCount: files.length,
          soId,
          description,
          uploader
        })
        
        const controller = new AbortController()
        const timeoutId = setTimeout(() => controller.abort(), 30000) // 30秒超时
        
        const response = await fetch('/api/sales/attachment/upload/batch', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          },
          body: formData,
          signal: controller.signal
        })
        
        clearTimeout(timeoutId)
        
        console.log('上传响应状态:', response.status)
        console.log('响应头:', Object.fromEntries(response.headers.entries()))
        
        if (!response.ok) {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`)
        }
        
        const result = await response.json()
        console.log('上传响应结果:', result)
        return result
        
      } catch (error) {
        lastError = error
        console.error(`上传尝试 ${attempt} 失败:`, error)
        
        if (error.name === 'AbortError') {
          console.error('请求超时')
          if (attempt < maxRetries) {
            console.log(`等待 ${attempt * 2} 秒后重试...`)
            await new Promise(resolve => setTimeout(resolve, attempt * 2000))
            continue
          }
        }
        
        if (error.message.includes('Failed to fetch') || error.message.includes('ERR_CONNECTION_ABORTED')) {
          console.error('网络连接错误，可能是后端服务未启动')
          if (attempt < maxRetries) {
            console.log(`等待 ${attempt * 2} 秒后重试...`)
            await new Promise(resolve => setTimeout(resolve, attempt * 2000))
            continue
          }
        }
        
        // 如果是最后一次尝试，返回详细错误信息
        if (attempt === maxRetries) {
          if (error.message.includes('Failed to fetch') || error.message.includes('ERR_CONNECTION_ABORTED')) {
            return { 
              success: false, 
              message: '网络连接失败，请检查后端服务是否启动',
              error: error.message,
              details: '请确保后端服务正在运行，并且端口8080可访问'
            }
          }
          return { 
            success: false, 
            message: '上传失败，请稍后重试',
            error: error.message
          }
        }
      }
    }
    
    return { 
      success: false, 
      message: '上传失败，已达到最大重试次数',
      error: lastError?.message
    }
  },

  // 下载附件
  downloadAttachment(attachmentId) {
    window.open(`/api/sales/attachment/download/${attachmentId}`)
  },

  // 批量下载附件（ZIP格式）
  async downloadAttachmentsAsZip(attachmentIds) {
    try {
      const response = await fetch('/api/sales/attachment/download/batch', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify(attachmentIds)
      })
      
      if (response.ok) {
        const blob = await response.blob()
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = 'attachments.zip'
        link.click()
        window.URL.revokeObjectURL(url)
        return { success: true, message: '下载成功' }
      } else {
        return { success: false, message: '下载失败' }
      }
    } catch (error) {
      console.error('批量下载失败:', error)
      return { success: false, message: '下载失败' }
    }
  },

  // 预览附件
  async previewAttachment(attachmentId) {
    try {
      const response = await fetch(`/api/sales/attachment/preview/${attachmentId}`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      if (response.ok) {
        const blob = await response.blob()
        return { success: true, data: blob }
      } else {
        return { success: false, message: '预览失败' }
      }
    } catch (error) {
      console.error('预览失败:', error)
      return { success: false, message: '预览失败' }
    }
  },

  // 删除附件
  async deleteAttachment(attachmentId) {
    try {
      const response = await fetch(`/api/sales/attachment/${attachmentId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      return response.json()
    } catch (error) {
      console.error('删除失败:', error)
      return { success: false, message: '删除失败' }
    }
  },

  // 批量删除附件
  async deleteAttachments(attachmentIds) {
    try {
      const response = await fetch('/api/sales/attachment/batch', {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify(attachmentIds)
      })
      return response.json()
    } catch (error) {
      console.error('批量删除失败:', error)
      return { success: false, message: '删除失败' }
    }
  }
}

// 导出所有接口
export default {
  // 客户相关接口
  getCustomerPage,
  createCustomer,
  updateCustomer,
  deleteCustomer,
  deleteCustomerBatch,
  
  // 订单相关接口
  createFullOrder,
  updateFullOrder,
  createOrder,
  getOrderPage,
  getOrderPageAdvanced,
  updateOrder,
  deleteOrderBatch,
  getOrderDetail,
  getFullOrderDetail,
  getOrderPrintData,
  printOrdersBatch,
  submitOrder,
  approveOrder,
  
  // 附件管理接口
  attachmentApi,
  attachmentTypeApi,
  fileApi
}


